package com.zws.cucumber.util;

import com.zws.cucumber.util.colorfullog.ZwsColorfulLogger;
import org.slf4j.Logger;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * author: zws
 */
public class ZwsPreparation {

    private static final Logger logger = ZwsColorfulLogger.of(ZwsPreparation.class);

    public static String loadFile(String filePath) {
        logger.debug("load body from file [{}]", filePath);
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource(filePath);
        if (!resource.exists()) {
            resource = resourceLoader.getResource("cucumber/data/" + filePath);
        }
        if (!resource.exists()) {
            logger.error("resource [{}] is not existed", filePath);
            throw new RuntimeException(new FileNotFoundException(filePath));
        }
        try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line).append(System.lineSeparator());
            }
            String body = sb.toString();
            logger.debug("body was loaded, body=[{}]", body);
            return body;
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    public static byte[] loadBinaryFile(String filePath) {
        logger.debug("load binary file [{}]", filePath);
        Resource resource = findResource(filePath);
        if (!resource.exists()) {
            logger.error("resource [{}] is not existed", filePath);
            throw new RuntimeException(new FileNotFoundException(filePath));
        }
        try (InputStream is = resource.getInputStream()) {
            return is.readAllBytes();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static Resource findResource(String filePath) {
        try {
            String fixedFilePath = filePath;
            if (!filePath.contains("/") && !filePath.startsWith("classpath")) {
                fixedFilePath = "classpath*:/**/" + filePath;
            }
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(fixedFilePath);
            logger.debug("resources: {}", Arrays.toString(resources));
            return resources[0];
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}
